# models.py
import uuid
from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    first_name = models.CharField(max_length=30, blank=True, null=True)
    last_name = models.CharField(max_length=150, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)  # 允许空值
    # 基本信息
    phone_number = models.CharField(max_length=20, blank=True, verbose_name="电话号码")
    name = models.CharField(max_length=10, blank=True, verbose_name="用户姓名")
    # 用户角色
    ROLE_CHOICES = [
        ('admin', '系统管理员'),
        ('user', '普通用户'),
    ]
    role = models.CharField(
        max_length=10,
        choices=ROLE_CHOICES,
        default='user',
        verbose_name="用户角色"
    )

    def __str__(self):
        return f"{self.username} ({self.get_role_display()})"

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"


class Category(models.Model):
    """文物类别模型"""
    id = models.AutoField(primary_key=True, verbose_name="类别ID")
    name = models.CharField(max_length=100, unique=True, verbose_name="文物主体名称")  # 唯一名称
    address = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name="地址信息",
        help_text="文物类别的地理位置或存放地址"
    )

    # 扩展字段
    construction_age = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        verbose_name="建筑年代",
        help_text="例如：清代、明代、民国等"
    )
    construction_type = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        verbose_name="建筑类型",
        help_text="例如：宫殿、庙宇、民居、塔等"
    )
    layout_orientation = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        verbose_name="建筑群整体布局方位",
        help_text="例如：坐北朝南、依山而建等"
    )
    protection_level = models.CharField(
        max_length=50,
        blank=True,
        null=True,
        verbose_name="保护级别",
        help_text="例如：国家级、省级、市级文物保护单位"
    )

    description = models.TextField(
        blank=True,
        null=True,
        verbose_name="文物主体描述",
        help_text="详细描述该文物类别的历史背景、文化价值等",
        max_length=None  # TextField 默认无限制，此处明确说明
    )

    image = models.ImageField(
        upload_to='category_images/',
        null=True,
        blank=True,
        verbose_name="文物主体图片"
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")    # 元数据：修复 related_name 冲突
    created_by = models.ForeignKey(
        'api.User',
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_categories",  # ✅ 修改：避免与 CulturalRelic 冲突
        verbose_name="创建人"
    )
    last_modified_by = models.ForeignKey(
        'api.User',
        on_delete=models.SET_NULL,
        null=True,
        related_name="modified_categories",  # ✅ 修改：避免与 CulturalRelic 冲突
        verbose_name="最后修改人"
    )

    class Meta:
        verbose_name = "文物主体"
        verbose_name_plural = "文物主体列表"
        # ordering = ["name"]
        ordering = ['created_at']  # 从小到大，即从旧到新

    def __str__(self):
        return self.name


class CulturalRelic(models.Model):
    """文物信息模型"""
    id = models.AutoField(primary_key=True, verbose_name="系统ID")  # 自动生成的唯一ID
    name = models.CharField(max_length=200, verbose_name="名称", help_text="必填，文物全称")
    image = models.ImageField(upload_to='relic_images/', verbose_name="图像", help_text="支持JPG/PNG格式")
    dynasty = models.CharField(max_length=100, null=True, blank=True, verbose_name="年代", help_text="如：唐代/19世纪")
    country = models.CharField(max_length=100, null=True, blank=True, verbose_name="国别", help_text="如：中国")

    building_type = models.CharField(max_length=100, null=True, blank=True, verbose_name="建筑类型")
    other_building_type = models.CharField(max_length=100, null=True, blank=True, verbose_name="其他建筑类型")

    category = models.ForeignKey(
        Category,
        # on_delete=models.SET_NULL,
        on_delete=models.CASCADE,  # 删除类别关联删除所有
        null=True,
        blank=True,
        related_name='relics',
        verbose_name="所属类别",
    )

    # 病害相关
    disease_types = models.CharField(
        max_length=200,
        null=True,
        blank=True,
        verbose_name="病害类型"
    )
    other_disease_types = models.CharField(
        max_length=200,
        null=True,
        blank=True,
        verbose_name="其他病害类型"
    )
    disease_severity = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        verbose_name="病害程度"
    )

    # 艺术特征字段
    pattern_types = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        verbose_name="纹样类型",
        help_text="多项用逗号分隔，例如：龙纹,云纹,莲花纹"
    )
    painting_theme = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        verbose_name="彩画主题",
        help_text="例如：宗教故事、神话传说、山水花鸟等"
    )
    composition_style = models.CharField(
        max_length=300,
        blank=True,
        null=True,
        verbose_name="构图形式",
        help_text="多项用逗号分隔，例如：对称式,中心放射式,连环画式"
    )
    dominant_colors = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        verbose_name="主色调",
        help_text="多项用逗号分隔，例如：朱红,青绿,金黄"
    )
    painting_technique = models.CharField(
        max_length=500,
        blank=True,
        null=True,
        verbose_name="彩画做法",
        help_text="例如：和玺彩画、旋子彩画、苏式彩画"
    )
    current_damage_status = models.TextField(
        blank=True,
        null=True,
        verbose_name="现状残损情况",
        help_text="描述当前文物的残损部位及状态"
    )

    # 光谱与3D数据
    hasSpectrum = models.BooleanField(default=False, verbose_name="是否已上传光谱文件")
    spectrum_file = models.FileField(
        upload_to='spectrum_files/',
        verbose_name="光谱数据文件",
        help_text="支持任意文件格式（如PDF/CSV/TXT）",
        blank=True,
        null=True
    )

    hasThreeD = models.BooleanField(default=False, verbose_name="是否有3D影像")
    threeD_file = models.FileField(
        upload_to='3d_files/',
        verbose_name="3D数据文件",
        help_text="支持任意文件格式（如OBJ/GLB/FBX）",
        blank=True,
        null=True
    )

    # 元数据
    created_by = models.ForeignKey(
        'api.User',  # ✅ 使用字符串引用自定义用户模型
        # User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_relics",
        verbose_name="创建人"
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_modified_by = models.ForeignKey(
        'api.User',
        # User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="modified_relics",
        verbose_name="最后修改人"
    )
    last_modified_at = models.DateTimeField(auto_now=True, verbose_name="最后修改时间")

    class Meta:
        verbose_name = "文物信息"
        verbose_name_plural = "文物信息列表"
        ordering = ["-created_at"]

    def __str__(self):
        return self.name


class DiseaseImage(models.Model):
    """文物病虫害图像模型（一对多关系）"""
    relic = models.ForeignKey(
        CulturalRelic,
        on_delete=models.CASCADE,
        related_name='disease_images',
        verbose_name="所属文物"
    )
    image = models.ImageField(upload_to='disease_images/', verbose_name="病虫害图像", help_text="支持JPG/PNG格式")
    description = models.TextField(null=True, blank=True, verbose_name="图像描述")
    image_name = models.TextField(null=True, blank=True, verbose_name="图像名称")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="上传时间")

    class Meta:
        verbose_name = "病虫害图像"
        verbose_name_plural = "病虫害图像列表"
        ordering = ["created_at"]

    def __str__(self):
        return f"{self.relic.name}的病虫害图像 #{self.id}"
